const MIN = 60;
const SEC = 1;

export const KARAOK = 'karaok';
export const SCROLL = 'scroll';

export function parseLyrics(lyrics) {
	const rows = lyrics.split('\n').filter((r) => r !== '');
	const dict = [];

	const tagReg = /\[([^[\]]+):([^[\]]*)\]/g;
	for (const row of rows) {
		const content = row.split(']').slice(-1)[0];

		let matched = tagReg.exec(row);
		while (matched) {
			const key = matched[1]?.trim();
			const value = matched[2]?.trim();

			const time = parseTag(key, value);
			time !== undefined && dict.push({ time, content });

			matched = tagReg.exec(row);
		}
	}

	dict.sort((a, b) => a.time - b.time);

	const current = (time) => dict.findLast((lyric) => lyric.time <= time) ?? '';

	const next = (time) => dict.find((lyric) => lyric.time > time) ?? '';

	return {
		[KARAOK]: { current, next },
		[SCROLL]: {
			content: dict.map((d) => d.content),
			current: (time) => dict.findLastIndex((lyric) => lyric.time <= time)
		}
	};
}

function parseTag(key, value) {
	const numReg = /^[0-9.]*$/;
	if ([key, value].every((v) => numReg.test(v))) {
		const min = key * MIN;
		const sec = value * SEC;
		const time = min + sec;
		return time;
	}
}
